;
(function (window, angular) {
    'use strict';
    var ybModule = angular.module("Service.ybModule", ['ajoslin.promise-tracker']);
    ybModule.config(['$httpProvider', function ($httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }

        $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';

        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache, no-store, must-revalidate';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
        $httpProvider.defaults.headers.get['Expires'] = '0';

        // <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />  
        // <meta http-equiv="Pragma" content="no-cache" />  
        // <meta http-equiv="Expires" content="0" />

        $httpProvider.defaults.headers.common = {
            'x-from-site':window.AppData.config.otherData.sysSite,
            'x-language': localStorage.getItem('lang') || 'zh-CN', // 中文:zh-CN 英文:en-US 西班牙文:es-ES 印度尼西亚:in 俄文:ru
            'app-v': '2022' // header增加标识app-v:2022，使老版本管理端app无法登录（兼容PC端：管理端app和PC端的x-from-site同为1）
        };
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.withCredentials = false;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        $httpProvider.interceptors.push('ybResponseInterceptor');
        $httpProvider.interceptors.push('ybRequestInjector');
    }]);
    ybModule.factory('ybResponseInterceptor', ['$q', '$injector', "$location", function ($q, $injector, $location) {
        var showLoginModalFlag = false;
        function handleResSuccess (response) {
            if (response.data.code == 2) {
                $injector.get('ybHttp').CancelTracker();
                
                if (!showLoginModalFlag) {
                    $injector.get('UserContextService').Logout(true, true);
                    $injector.get('ybWidget').ShowLoginModal();//通过手动注入的方式防止循环依赖
                    showLoginModalFlag = true;
                }
                return $q.defer().promise;
            }
            return response;
        }
        function handleResError (rejection) {
            var status = rejection.status;
            var errMsg = '';
            if (status === 0) {
                errMsg = "网络出现未知的错误，请检查您的网络。"
            }
            if (status >= 300 && status < 400) {
                errMsg = '请求被服务器重定向，状态码为' + status;
            }
            if (status >= 400 && status < 500) {
                errMsg = '客户端出错，可能是发送的数据有误，状态码为' + status;
            }
            if (status >= 500) {
                errMsg = '服务器发生错误，状态码为' + status;
            }

            errMsg += "<div class='table-word-break'>URL:" + rejection.config.url + '</div>';

            $injector.get('ybWidget').ShowMessage(errMsg, $injector.get('MESG_TYPE').Error, {isHtml: true}); ////通过手动注入的方式防止循环依赖
            return $q.reject(rejection);
        }
        return {
            response: function (response) {
                return handleResSuccess(response);
            },
            responseError: function (rejection) {
                return handleResError(rejection);
            }
        };
    }]);
    ybModule.factory('ybRequestInjector', ["$q", "$injector", "$filter", function ($q, $injector, $filter) {
        return {
            request: function (config) {
                config.headers["SC-AUTH"] = localStorage.getItem("ScAuthC");
                return config;
            }
        };
    }]);
    ybModule.factory("ybHttp", ["$rootScope", "$http", "$q", "ybConfig", "promiseTracker", function ($rootScope, $http, $q, ybConfig, promiseTracker) {
        $rootScope.loadingTracker = promiseTracker({activationDelay: 800});

        function _GetRequestUrl(serviceName, url) {
            var config = ybConfig.getConfig();
            return config.baseUrl.Site + (config.serviceName[serviceName] || '') + url;
        }

        function _Post(serviceName, url, formData) {
            var deferred = $q.defer();
            var needTracker = true;
            var resp = $http.post(_GetRequestUrl(serviceName, url), formData, needTracker ? {tracker: $rootScope.loadingTracker} : {});
            resp.then(function (data, status, headers, config) {
                deferred.resolve(data.data);
            },
            function (data, status, headers, config) {
                deferred.reject({Code: data.status, Message: "服务器发生错误"});
            });
            return deferred.promise;
        }

        function _Get(serviceName, url, param, config) {
            var deferred = $q.defer();
            $http.get(_GetRequestUrl(serviceName, url), {
                params: param,
                responseType: !!config ? (config.responseType || undefined) : undefined,
                tracker: $rootScope.loadingTracker
            }).then(function (data, status, headers, config) {
                deferred.resolve(data.data);
            },
            function (data, status, headers, config) {
                deferred.reject({Code: data.status, Message: "服务器发生错误"});
            });
            return deferred.promise;
        }
        function _ImgUrl(key, sizeParam) {
            if (angular.isString(key) == false || !key) {
                return "";
            }
            if (key.indexOf("http") != -1 || key.indexOf("asset") != -1) {
                return key;
            }
            if (!!sizeParam) {
                key += "!";
                key += sizeParam;
            }
            return ybConfig.getConfig().baseUrl.Image + key;
        }

        function _CancelTracker() {
            $rootScope.loadingTracker.cancel();
        }

        return {
            Post: _Post,
            Get: _Get,
            ImgUrl: _ImgUrl,
            RequestUrl: _GetRequestUrl,
            CancelTracker: _CancelTracker
        }
    }]);
    ybModule.factory("ybConfig", ["$q", "$log", function ($q, $log) {
        var _config;
        return {
            initConfig: function() {
                _config = window.AppData.config
            },
            getConfig: function() {
                return _config;
            },
            isEnvProd: function() {
                return ['10.1.1.245', 'xgbj.xcmg.com:19000'].includes(window.location.host)
            },
            isPublicNetwork: function() {
                return ['pms.hanyunapp.cn', 'xgbj.xcmg.com:19000'].includes(window.location.host)
            }
        }
    }]);
    ybModule.service("EventBus", [function () {
        var subscriberList = [];

        function _subscribe(evt, fn) {
            for (var i = 0; i < subscriberList.length; ++i) {
                if (subscriberList[i].Event === evt && subscriberList[i].Fn === fn) {
                    return;
                }
            }
            subscriberList.push({Event: evt, Fn: fn});
        }

        function _unsubscribe(evt, fn) {

            for (var i = 0; i < subscriberList.length; ++i) {
                if (subscriberList[i].Event === evt && subscriberList[i].Fn === fn) {
                    break;
                }
            }
            subscriberList.splice(i, 1);

        }

        function _publish(evt, data) {
            var result = null;
            for (var i = 0; i < subscriberList.length; ++i) {
                if (subscriberList[i].Event === evt) {
                    result = subscriberList[i].Fn(data);
                }
            }
            return result;
        }

        return {
            Subscribe: _subscribe,
            Unsubscribe: _unsubscribe,
            Publish: _publish
        };
    }]);
    ybModule.factory("ybNavigator", ["$injector", "MESG_TYPE", function ($injector,MESG_TYPE) {
        function _fnIsIE8Browser() {
            if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.split(";")[1].replace(/[ ]/g, "") == "MSIE8.0") {
                return true;
            }
            return false;
        }

        function _fnIsIEBrowser() {
            if (!!window.ActiveXObject||'ActiveXObject' in window) {
                return true;
            }
            return false;
        }

        /**Parses string formatted as YYYY-MM-DD to a Date object.
         * If the supplied string does not match the format, an
         * invalid Date (value NaN) is returned.
         * @param {string} dateStringInRange format YYYY-MM-DD, with year in
         * range of 0000-9999, inclusive.
         * @return {Date} Date object representing the string.
         */
        function _fnParseNewDate(dateStringInRange) {
            var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
                date = new Date(NaN), month,
                parts = isoExp.exec(dateStringInRange);

            if (parts) {
                month = +parts[2];
                date.setFullYear(parts[1], month - 1, parts[3]);
                if (month != date.getMonth() + 1) {
                    date.setTime(NaN);
                }
            }
            return date;
        }

        function _fnShowFlashHint(){
            if(angular.isUndefined(window.FileAPI.hasFlash) || window.FileAPI.hasFlash){
                return;
            }
            var content = "你的浏览器版本过低，需要安装<a href='https://get.adobe.com/flashplayer/?loc=cn' " +
                "target='_blank' class='danger-color' title='Adobe Flash Player'><span class='danger-color'>Adode Flash Player</span></a>" +
                "，如果已安装了，请确认Activex控件是否在浏览器启用，操作完成后请重新打开浏览器";
            $injector.get('ybWidget').ShowMessage(content, MESG_TYPE.ERROR, {isHtml:true});
        }

        return {
            IsIE8: _fnIsIE8Browser,
            ParseNewDate: _fnParseNewDate,
            ShowFlashHint: _fnShowFlashHint,
            IsIE: _fnIsIEBrowser
        }

    }]);
})(window, window.angular);